package com.interfaces.util;

import com.interfaces.config.RedisCache;
import com.interfaces.enumeration.TOKEN_TIME_TYPE;
import com.interfaces.enumeration.TOKEN_TYPE;
import com.interfaces.module.user.domain.FtsUser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

/**
 * @author
 * @date
 * token工具类
 */
@Component
public class TokenUtil {
    @Autowired
    private RedisCache cache;
    public static TokenUtil tokenUtil;
    public static String expireType;

    @Value("${token.expireType}")
    public void setExpireType(String expireType) {
        TokenUtil.expireType = expireType;
    }
    @PostConstruct
    public void init(){
        tokenUtil = this;
        tokenUtil.cache = this.cache;
    }

    public static Integer cacheTime;
    @Value("${token.expireTime}")
    public void setCacheTime(Integer cacheTime){
        TokenUtil.cacheTime =cacheTime;
    }
    /**
     * 获取token信息
     * @return
     */
    public static String getToken(){
        ServletRequestAttributes servletRequestAttributes =  (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        return request.getHeader(TOKEN_TYPE.TOKEN.name());
    }

    /**
     * 根据token获取用户信息
     * @return
     */
    public static FtsUser getTokenUser(){
        String token=getToken();
        FtsUser user=tokenUtil.cache.getCacheObject(token);
        return user;
    }

    /**
     * 更新token
     * @param user
     */
    public static void tokenUserUpdate(FtsUser user){
        String token=getToken();
        if(StringUtils.isNotEmpty(token)){
            TimeUnit timeUnit;
            switch (TOKEN_TIME_TYPE.getByValue(expireType)) {
                case MINUTES:
                    timeUnit = TimeUnit.MINUTES;
                    break;
                case DAYS:
                    timeUnit = TimeUnit.DAYS;
                    break;
                case HOURS:
                    timeUnit = TimeUnit.HOURS;
                    break;
                default: timeUnit=TimeUnit.SECONDS;;
                    break;
            }
            tokenUtil.cache.putCacheObject(token,user,cacheTime,timeUnit);
        }

    }
}
